package pool

import (
	"gitee.com/zhongguo168a/gocodes/datax/arrayx"
)

func NewPool() (obj *Pool) {
	obj = &Pool{}
	return
}

type Pool struct {
	items   []interface{}
	count   int
	creator func(...interface{}) interface{}
}

func (p *Pool) SetCreator(c func(...interface{}) interface{}) {
	p.creator = c
}

func (p *Pool) Dispose() {
	p.items = nil
}
func (p *Pool) Count() int {
	return p.count
}

func (p *Pool) GetItem() (r interface{}) {
	a := p.items
	p.count++
	l := len(a)
	if l == 0 {
		return
	} else {
		r, p.items = a[len(a)-1], a[:len(a)-1]
	}

	return
}

func (p *Pool) GetOrNewItem(args ...interface{}) (r interface{}) {
	a := p.items
	p.count++
	l := len(a)
	if l == 0 {
		if p.creator == nil {
			return
		}
		r = p.creator(args...)
	} else {
		r, p.items = a[len(a)-1], a[:len(a)-1]
	}

	return
}

func (p *Pool) PutItem(r interface{}) {
	items := p.items
	p.items = append(items, r)
	p.count--
}
func (p *Pool) Contains(r interface{}) bool {
	items := p.items
	i := arrayx.IndexOf(len(items), func(i int) bool {
		return items[i] == r
	})
	return i != -1
}
